<?php
class Soul_Cache_File{
	
	private $_caches = array();
	
	private function __construct(){
		if(file_exists(Soul_Cache_Config::$cacheDirectory.'__filecaches__')){
			$this->_caches = unserialize(file_get_contents(Soul_Cache_Config::$cacheDirectory.'__filecaches__'));
		}
		$now = time();
		foreach($this->_caches as $name=>&$item){
			if($item['expiry'] <= $now){
				Soul_Util_FS::deleteFile(Soul_Cache_Config::$cacheDirectory.$name);
			}
			unset($this->_caches[$name]);
		}
	}
	
	public function cache($name, $data, $expiry){
		$this->_caches[$name] = array('expiry'=>$expiry);
		$content = '';
		if(is_array($data)){
			$content = serialize($data);
			$this->_caches[$name]['type'] = 'array';
		}elseif(is_object($data)){
			$content = serialize($data);
			$this->_caches[$name]['type'] = 'object';
		}else{
			$content = $data;
			$this->_caches[$name]['type'] = 'string';
		}
		file_put_contents(Soul_Config::$cacheDirectory.$name, $content);
		return $this;
	}
	
	public function remove($name){
		if($this->exists($name)){
			unset($this->_caches[$name]);
			Soul_Util_FS::deleteFile(Soul_Config::$cacheDirectory.$name);
		}
		return $this;
	}
	
	public function exists($name){
		return isset($this->_caches[$name]);
	}
	
	public function __destruct(){
		file_put_contents(Soul_Config::$cacheDirectory.'__filecaches__', serialize($this->_caches));
	}
	
	private static $_instance = NULL;
	public static function getInstance(){
		if(is_null(self::$_instance)){
			self::$_instance = new self();
		}
		
		return self::$_instance;
	}
}